package com.ftg.learn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ftg.learn.dto.LoginDto;
import com.ftg.learn.entity.AdminUser;
import com.ftg.learn.mapper.AdminUserMapper;
import com.ftg.learn.service.IAdminUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.util.JwtUtils;
import com.ftg.learn.util.Md5Utils;
import com.ftg.learn.util.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 布衣
 * @since 2025-07-22
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements IAdminUserService {

    @Override
    public R<Map<String, Object>> login(LoginDto loginRequest) {
        QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginRequest.getUsername());
        AdminUser adminUser = this.getOne(queryWrapper);
        if(adminUser == null){
            return R.failure("用户不存在");
        }
        if(StringUtils.isBlank(loginRequest.getPassword())){
            return R.failure("密码不能为空");
        }

        String pass_hash = Md5Utils.md5(loginRequest.getPassword());

        if(adminUser.getPwdHash().equals(pass_hash)){
            Map<String,Object> user = new HashMap<>();
            user.put("id",adminUser.getId());
            user.put("username",adminUser.getUsername());
            user.put("role",adminUser.getRole());
            String token = JwtUtils.generateToken("loginJwt", user);


            Map<String,Object> reMap = new HashMap<>();
            reMap.put("token",token);
            reMap.put("id",adminUser.getId());
            return R.ok(reMap);
        }
        return R.failure("密码错误");
    }
}
